package com.example.miniofenpian.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.example.miniofenpian.config.OssConfig;
import com.example.miniofenpian.service.FileService;
import com.example.miniofenpian.util.AmazonS3Util;
import com.example.miniofenpian.util.Constant;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;

/**
 * @author fulin
 * @since 2024/9/20 10:29
 */
@Service
public class LocalServiceImpl implements FileService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public boolean handel() {
        return Constant.OSSType.LOCAL.name().equalsIgnoreCase(redisTemplate.opsForValue().get(Constant.OSS_CONFIG_KEY));
    }

    @SneakyThrows
    @Override
    public String upload(MultipartFile file) {
        String originalFilename = IdUtil.fastSimpleUUID() + StrUtil.UNDERLINE + file.getOriginalFilename();
        FileUtil.writeFromStream(file.getInputStream(), Constant.LOCAL_FILE_PATH + originalFilename);
        return getSchemeUrl() + originalFilename;
    }

    @SneakyThrows
    public static String getSchemeUrl() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        // 获取当前请求的协议（http或https）
        String scheme = request.getScheme();
        // 获取当前请求的主机名（IP地址）
        String hostName = InetAddress.getLocalHost().getHostAddress();
        // 获取当前请求的端口号
        int port = request.getServerPort();
        // 构造完整的URL
        return scheme + StrUtil.COLON + StrUtil.SLASH + StrUtil.SLASH + hostName + StrUtil.COLON + port + Constant.LOCAL_FILE_PREFIX;
    }
}
